package mspbots.autotask.data.core.contactgroups;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.autotask.common.ResultMsg;
import org.springframework.stereotype.Component;

import java.time.Duration;

@Log4j2
@Component
@RequiredArgsConstructor
public class ContactGroupsReceiver {

    private final ContactGroupsRepository contactGroupsRepository;

//    @RabbitListener(queues = "auto-task.contact-groups.sync")
    public void syncTask(ResultMsg content) {
        ContactGroup contactGroup = ContactGroup.builder().otherId(content.getId())
                .tenantId(content.getTenantId()).syncTime(content.getSyncDate())
                .entity(content.getEntity())
                .build();


        this.contactGroupsRepository.findByOtherIdAndTenantId(content.getId(), content.getTenantId())
                .map(ticket -> {
                    contactGroup.setId(ticket.getId());
                    return contactGroup;
                })
                .defaultIfEmpty(contactGroup)
                .flatMap(this.contactGroupsRepository::save)
                .block(Duration.ofSeconds(10));
    }
}
